#include "data_transmit.h"
#include "protocol.h"


static void Inqueue(void *arg,uint8_t *pack,uint32_t len)
{
	DT_PackInque_TypeDef *queue = (DT_PackInque_TypeDef*)arg;
	
	if( len > MAX_QUEUE_PACK_SIZE || len == 0)
		return;

	memcpy( queue->queue[queue->tail],pack,len);
	queue->pack_size[queue->tail] = len;
	queue->tail+=1;
	if(queue->tail >= MAX_QUEUE_LENGTH)
	{
		queue->tail = 0;
	}
	queue->empty_flag = 0;
	if(queue->tail == queue->head)
	{
		queue->head += 1;
		if(queue->head >= MAX_QUEUE_LENGTH)
		{
			queue->head = 0;
		}
		queue->full_flag = 1;
	}
	
}


static uint32_t Dequeue(void *arg,uint8_t *pack)
{
	DT_PackInque_TypeDef *queue = (DT_PackInque_TypeDef*)arg;
	
	if( queue->head == queue->tail )
	{
		queue->empty_flag = 1;
		return 0;	
	}
	memcpy( pack,queue->queue[queue->head],queue->pack_size[queue->head]);
	uint32_t ret = queue->pack_size[queue->head];
	queue->head += 1;

	queue->full_flag =  0 ;
	if(queue->head >= MAX_QUEUE_LENGTH)
	{
		queue->head = 0;
	}
	return ret;
}

DT_PackInque_TypeDef hc_queue=
{
	.head = 0,
	.tail = 0,
	.inqueue = Inqueue,
	.dequeue = Dequeue,
	.empty_flag = 1,
	.full_flag = 0,
};


void HC_DataInqueue(uint8_t *pack,uint32_t len)
{
	hc_queue.inqueue(&hc_queue,pack,len);
}

uint32_t HC_DataDequeue(uint8_t *pack)
{
	return hc_queue.dequeue(&hc_queue,pack);
}


char fmt_buf[ MAX_QUEUE_PACK_SIZE - sizeof(protocol_header_t) - sizeof(uint32_t) ] = "\0"; 
uint8_t pack[MAX_QUEUE_PACK_SIZE] = {0};
uint32_t pack_len;
int fmt_len;
void hc_printf(const char *fmt,...)
{
	memset(fmt_buf,0,sizeof(fmt_buf));
	va_list args;
	va_start(args, fmt);
	fmt_len = vsnprintf(fmt_buf, sizeof(fmt_buf), fmt, args);
	va_end(args);	

	
	pack_len = protocol_print_pack(pack, sizeof(pack),fmt_buf,fmt_len);
	
	HC_DataInqueue(pack,pack_len);
}




